/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.gui;

import it.polimi.deib.se2.meteocal.business.boundary.UserManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@Named
@RequestScoped
public class LoginBean {
    
    @Inject
    private Logger logger;
    
    @EJB
    private UserManager um;
    
    private String username;
    private String password;
    
    public LoginBean() {
    }
    
    public String getUsername() {
        return this.username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return this.password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
        
    public UserManager getUm() {
        return um;
    }
    
    public void setUm(UserManager um) {
        this.um = um;
    } 
    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.username, this.password);
            boolean noNotifications = getUm().find(username).getNotifications().isEmpty();
            if(!noNotifications){
                return "user/notifications?faces-redirect=true";
            }else
                return "user/home?faces-redirect=true";
        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login Failed","Login Failed"));
            logger.log(Level.SEVERE,"Login Failed");
            return null;
        }
    }
    
    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        request.getSession().invalidate();
        logger.log(Level.INFO, "User Logged out");
        return "/login?faces-redirect=true";
    }
}
